package org.example.algo;

/**
 * 双链表
 * @author shenguangyang
 */
public class N06_DoubleLinked {
    public static void main(String[] args) {
        Linked linked = new Linked();
        linked.addLast(new Node(1));
        linked.addLast(new Node(3));
        linked.addLast(new Node(5));
        linked.addLast(new Node(7));
        printf(linked.head);
        printf(reverseLinked(linked.head));

    }
    public static class Linked {
        Node head;

        public Linked() {
            this.head = null;
        }

        public void addLast(Node node) {
            if (this.head == null) {
                this.head = node;
                return;
            }

            Node cur = head;
            while (cur.next != null) {
                cur = cur.next;
            }
            cur.next = node;
            node.pre = cur;
        }
    }

    public static class Node {
        int value;
        Node next;
        Node pre;

        public Node(int value) {
            this.value = value;
        }
    }

    public static void printf(Node head) {
        if (head == null) {
            return;
        }
        System.out.println("printf ========== start");
        Node cur = head;
        while (cur != null) {
            System.out.println(cur.value);
            cur = cur.next;
        }
        System.out.println("printf ========== end\n");
    }

    /**
     * 反转链表
     */
    public static Node reverseLinked(Node head) {
        if (head == null || head.next  == null) {
            return null;
        }

        Node next;
        Node pre = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            head.pre = next;
            pre = head;
            head = next;
        }
        return pre;
    }
}
